<script setup lang="ts">
import { h, onDeactivated, onMounted, ref, watchEffect } from 'vue';
import { NButton, NIcon, NProgress, useDialog, useMessage } from 'naive-ui';
import { AlertCircle, CheckmarkCircleSharp } from '@vicons/ionicons5';
import type { DataTableColumns } from 'naive-ui';
import { useRoute, useRouter } from 'vue-router';
import * as htmlDocx from 'html-docx-js-typescript';
import { saveAs } from 'file-saver';
import { useRouterPush } from '@/hooks/common/router';
import {
  cancelTaskGenerateAction,
  deleteBid,
  getKnowledgeListAction,
  getSaasUserDrop,
  historyWriteListAction
} from '@/service/api';
import { successMessage } from '@/utils/utils';

interface Song {
  no: number;
  title: string;
  length: string;
  state?: number;
}

const dialog = useDialog();

function handleDelete(row: any) {
  dialog.info({
    title: '删除标书',
    content: '请问是否确认删除该标书？',
    positiveText: '确定',
    negativeText: '返回',
    onPositiveClick: async () => {
      const { data, error } = await deleteBid(row.id);
      // 算法取消排队接口
      if (row.catalogStatus == 0) {
        await cancelTaskGenerateAction({
          task_id: row.id
        });
      }
      if (!error) {
        message.success('已删除');
        getTableList();
      }
    },
    onNegativeClick: () => {
      message.warning('已取消');
    }
  });
}

const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;

const otherUrl: any = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);

const imgUrl = otherUrl.imgUrl;

// 下载标书
function downloadBid(row: any) {
  // let aLink = document.createElement("a");
  // aLink.style.display = "none";
  // aLink.href = imgUrl + row.filePath;
  // document.body.appendChild(aLink);
  // aLink.click();
  // document.body.removeChild(aLink);
  // message.success("下载成功");

  const fileStr = row.filePath;
  if (fileStr.includes('.docx')) {
    saveAs(imgUrl + fileStr, `${row.title}.docx`, { encoding: 'UTF-8' });
    successMessage('文档下载成功');
  } else {
    let htmlContentStr: string = row.filePath;
    // console.log("htmlContentStr: ", htmlContentStr);

    htmlContentStr = htmlContentStr.replace(/<img /g, '<img width="650" height="650"');
    // 设置表格边框
    const htmlContent = htmlContentStr.replaceAll(/<table/g, `<table border-collapse="collapse" border="1" `);

    const formatContent = `
    	 	<!DOCTYPE html>
    	 	<html lang="en">
          <head>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <title>${row.title}</title>
          </head>
          <body>
             ${htmlContent}
          </body>
        </html>`;

    const convertedFile = htmlDocx.asBlob(formatContent);

    // 生成链接并且下载
    convertedFile.then(fileData => {
      saveAs(fileData as Blob, `${row.title}.docx`, { encoding: 'UTF-8' });
      successMessage('文档下载成功');
    });
  }
}

interface Formtype {
  searchValue: string;
  pageNum: number;
  pageSize: number;
  catalogStatus: Number;
  biddingUnit?: Number;
  userId?: Number;
  startTime?: String;
  endTime?: String;
}

const searchVal = ref('');

const formData = ref<Formtype>({
  searchValue: '',
  pageNum: 1,
  pageSize: 10,
  catalogStatus: 1
});

const pageCount = ref<number>();

const dataList = ref([]);

const catalogStatusObj = ref({
  0: '生成中' + ' 🕜',
  1: '生成完成' + ' ✅',
  2: '生成失败' + ' ⚠'
});

const bidObj = ref({
  0: '陪标',
  1: '标书'
});

const sourceObj = ref({
  0: '陪标',
  1: '标书'
});

// 行业类型(1.软件类 2.服务类 3.货物类 4.工程类 5.管理 6.设计 7.技术 8.经济类 20.其他)
const industryObj = ref({
  1: '软件类',
  2: '服务类',
  3: '货物类',
  4: '工程类',
  5: '管理类',
  6: '设计类',
  7: '技术类',
  8: '经济类',
  20: '其他'
});

const tableLoading = ref(false);

async function getTableList() {
  tableLoading.value = true;
  const { data, error } = await historyWriteListAction(formData.value);
  if (!error) {
    dataList.value = data?.records;
    pageCount.value = data?.pages;
    tableLoading.value = false;
  }
}

const route = useRoute();
// 获取params

onMounted(() => {
  if (route.query.searchValue) {
    searchVal.value = route.query.searchValue;
    handleSearch();
  } else {
    getTableList();
  }
  getKnowledgeListData();
  getSaasUserDropList();
});

let timer: any;

onDeactivated(() => {
  clearInterval(timer);
});

const router = useRouter();

// watch (
//   () => router.currentRoute.value.query.tab,
//   (to, from) => {
//     if (router.currentRoute.value.query.tab == "1") {
//       console.log("刷新");
//       // 组件激活时立即调用
//       getTableList();
//       timer = window.setInterval(() => {
//         getTableList();
//       }, 10000);
//     } else {
//       console.log("取消");
//       clearInterval(timer);
//     }
//   },
// );

watchEffect(() => {
  if (router.currentRoute.value.query.tab == '1') {
    console.log('刷新');
    // 组件激活时立即调用
    getTableList();
    timer = window.setInterval(() => {
      getTableList();
    }, 10000);
  } else {
    console.log('取消');
    clearInterval(timer);
  }
});

const knowledgeList = ref<any[]>([]);

// 获取知识库信息
async function getKnowledgeListData() {
  const params: any = {};
  const { data, error } = await getKnowledgeListAction(params);
  if (!error) {
    knowledgeList.value = data;
  }
}

const createUserList = ref<any[]>([]);

// 获取知识库信息
async function getSaasUserDropList() {
  const { data, error } = await getSaasUserDrop();
  if (!error) {
    createUserList.value = data;
  }
}

function createColumns({ play }: { play: (row: Song) => void }): DataTableColumns<Song> {
  return [
    {
      title: '序号',
      align: 'center',
      key: 'key',
      render: (_, index) => {
        return `${(formData.value.pageNum - 1) * formData.value.pageSize + index + 1}`;
      }
    },
    {
      title: '标书名',
      key: 'title',
      align: 'center',
      ellipsis: {
        tooltip: true
      },
      width: '240px'
    },
    {
      title: '标书行业',
      key: 'industryType',
      align: 'center',
      render(row: any) {
        return industryObj.value[row.industryType];
      }
    },
    // {
    //   title: "素材来源",
    //   key: "materialType",
    //   align: "center",
    //   render(row: any) {
    //     return sourceObj.value[row.materialType];
    //   },
    // },
    {
      title: '应标单位',
      key: 'biddingUnit',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '目录创建时间',
      key: 'catalogCreateTime',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '创建人',
      key: 'nickName',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '最后操作时间',
      key: 'updateTime',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '最后操作人',
      key: 'updateNickName',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '撰写进度',
      key: 'catalogDataStatus',
      align: 'center',
      render(row: any) {
        if (row.catalogDataStatus == 0) {
          return [
            h(
              NProgress,
              {
                type: 'line',
                percentage: Math.floor(Number((row.finishNum / row.catalogNum) * 100)),
                processing: true,
                showIndicator: true,
                indicatorPlacement: 'inside'
              },
              {}
            )
          ];
        } else if (row.catalogDataStatus == 1) {
          return [
            h(
              'div',
              {
                class: 'flex justify-center'
              },
              [
                h(
                  NIcon,
                  { color: '#68BF7B', size: '22px' },
                  {
                    default: () => h(CheckmarkCircleSharp)
                  }
                ),
                h('span', { class: 'ml-3px lh-23px' }, ['已完成'])
              ]
            )
          ];
        }
        return [
          h(
            'div',
            {
              class: 'flex justify-center'
            },
            [
              h(
                NIcon,
                { color: '#FF7575', size: '22px' },
                {
                  default: () => h(AlertCircle)
                }
              ),
              h('span', { class: 'ml-3px' }, ['生成失败'])
            ]
          )
        ];
      }
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      render(row: any) {
        return [
          h(
            NButton,
            {
              type: 'info',
              strong: true,
              tertiary: true,
              onClick: () => handleEdit(row)
            },
            { default: () => '编辑' }
          )
        ];
      }
    }
  ];
}
const columns: any = createColumns({
  play(row: Song) {
    message.info(`Play ${row.title}`);
  }
});

const message = useMessage();

interface Props {
  /** 左侧标题 */
  title?: string;
  /** 右侧按钮是否显示 */
  rightShow?: boolean;
  /** 右侧按钮标题 */
  rightTitle?: string;
  /** 右侧按钮图标是否展示 */
  iconShow?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  rightShow: false,
  rightTitle: '',
  iconShow: false
});

// const rightImg = computed(() => {
//   return props.rightIcon ? `@/assets/imgs/${props.rightIcon}` : '';
// })

const emit = defineEmits(['backClick', 'rightButtonClick']);

// 返回上一页
function goBackClick() {
  emit('backClick');
}

const { routerPushByKey } = useRouterPush();

// 编辑
function handleEdit(row: any) {
  // const pushParams: any = {
  //   generateType: 1,
  //   taskId: row.id,
  //   fileName: row.title,
  // };
  // routerPushByKey("document_detail", { query: pushParams });

  // 标书行业：industryObj.value[row.industryType]

  const infoPath = [
    `项目名称：${row.title}`,
    `方案类型：${industryObj.value[row.industryType]}`,
    `采购单位：${row.tenderingUnit}`,
    `应标单位：${row.biddingUnit}`
  ];

  const pushParams: any = {
    generateType: 1,
    taskId: row.id,
    fileName: row.title,
    infoPath: infoPath.join(','),
    zhaoBiaoPath: row.more1,
    catalogPath: row.originalFilePath,
    isOneClickWrite: row.catalogDataStatus
  };
  routerPushByKey('document_catalog', { query: pushParams });
}

// 右侧按钮点击事件
function rightButtonClick() {
  emit('rightButtonClick');
}

// 搜索
function handleSearch() {
  formData.value.pageNum = 1;
  getTableList();
}

function changeTimeRange(val: any) {
  if (val) {
    formData.value.startTime = val[0];
    formData.value.endTime = val[1];
  } else {
    formData.value.startTime = undefined;
    formData.value.endTime = undefined;
  }
}
</script>

<template>
  <div class="w-full">
    <div class="title">标书生成记录</div>
    <!--
 <div class="search-box">
      <n-input
        placeholder="请输入项目名称"
        size="large"
        v-model:value="searchVal"
        @keyup.enter.native="handleSearch"
        clearable
      >
        <template #suffix>
          <n-button text style="font-size: 24px" @click="handleSearch">
            <n-icon :component="Search" />
          </n-button>
        </template>
      </n-input>
    </div>
-->
    <NForm
      ref="formRef"
      style="margin-top: 30px; margin-left: 30px"
      inline
      label-width="auto"
      :model="formData"
      label-placement="left"
      size="large"
    >
      <NFormItem label="项目名称" path="searchValue">
        <NInput v-model:value="formData.searchValue" clearable placeholder="请输入项目名称" />
      </NFormItem>
      <NFormItem label="创建人" path="userId">
        <NSelect
          v-model:value="formData.userId"
          clearable
          style="width: 150px"
          :options="createUserList"
          label-field="nickName"
          value-field="userId"
        />
      </NFormItem>
      <NFormItem label="应标单位" path="biddingUnit">
        <NSelect
          v-model:value="formData.biddingUnit"
          clearable
          style="width: 250px"
          :options="knowledgeList"
          label-field="folderName"
          value-field="folderName"
        />
      </NFormItem>
      <NFormItem label="生成时间" path="range">
        <NDatePicker
          v-model:formatted-value="formData.range"
          style="width: 400px"
          type="datetimerange"
          clearable
          value-format="yyyy-MM-dd HH:mm:ss"
          :on-update:formatted-value="changeTimeRange"
          :default-time="['00:00:00', '23:59:59']"
        />
      </NFormItem>
      <NFormItem>
        <img
          style="width: 120px; cursor: pointer; margin-left: 35px"
          src="@/assets/bid-materials/search-img.png"
          alt=""
          @click="handleSearch"
        />
      </NFormItem>
    </NForm>
    <div class="table-area">
      <NDataTable
        striped
        size="small"
        :loading="tableLoading"
        :columns="columns"
        :data="dataList"
        :bordered="false"
        style="height: 610px; font-size: 18px; color: #666666"
      />
      <NPagination
        v-model:page="formData.pageNum"
        v-model:page-size="formData.pageSize"
        size="medium"
        style="float: right; margin-right: 20px; margin-bottom: 10px"
        :page-count="pageCount"
        @update:page="getTableList"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.title {
  font-weight: 500;
  font-size: 19px;
  color: #333333;
  line-height: 48px;
  padding-left: 50px;
  margin-top: 4px;
  border-bottom: #ebeef5 1px solid;
}
.search-box {
  margin-top: 30px;
  margin-left: 32px;
  width: 464px;
  height: 54px;
}
.table-area {
  margin-top: 10px;
  margin-left: 32px;
  width: 1471px;
  height: 400px;
  :deep(.n-data-table .n-data-table-th) {
    background-color: #f2f0ff;
    height: 60px;
    color: #333333;
    font-size: 18px;
  }
}
</style>
